// pages/mycomment/index.js
import {User} from "../../model/User.js";
import {Utils} from "../../utils/util.js";
const user = new User();
const utils = new Utils();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    comments: [],
    upload: false,
    loadtype: "loading"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getComments({
      type:"first"
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this._getComments({
      type:"first"
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.loadtype != "end") {
      this.setData({
        upload: true,
        loadtype: "loading"
      });
      this._getComments({
        type: "more"
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  _getComments(options){
    if (options.type == "first") {
      this.setData({
        loadtype: "loading"
      });
    }
    user.getMyComment(options)
      .then(res=>{
        let comments = res.data.Results.map((comment)=>{
          comment.CreateTime = utils.timestampFormat(comment.CreateTime);
          let post = comment.Post;
          comment.postImgArr = post.Images.split(",");
          comment.postVideoArr = post.Videos.split(",");
          comment.postContent = post.Content.substr(0,15);
          return comment
        });

        if (options.type == "first") {
          wx.stopPullDownRefresh();
          this.setData({
            comments: []
          });
          this.setData({
            comments: comments
          });
        } else {
          this.setData({
            comments: this.data.comments.concat(comments),
            upload: false
          })
        }

        if (res.data.TotalPage <= res.data.Page) {
          this.setData({
            upload: true,
            loadtype: "end"
          });
        }
      })
      .catch(err=>{
        wx.showToast({
          title: err.msg,
          icon:"none"
        })
      });
  },
  /**
   * 跳转帖子详情
   */
  gotoDetail(e){
      const id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: `/pages/detail/index?id=${id}`,
      })
  }
})